import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/blogDelete")
public class BlogDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.获取用户的登陆状态
        HttpSession session = req.getSession(false);
        if (session == null){
            resp.setContentType("text/html; charset=utf8");
            resp.setStatus(403);
            resp.getWriter().write("当前用户未登录,无法删除博客!");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null){
            resp.setContentType("text/html; charset=utf8");
            resp.setStatus(403);
            resp.getWriter().write("当前用户未登录,无法删除博客!");
            return;
        }
        // 2.获取到blogId
        String blogId = req.getParameter("blogId");
        if (blogId == null){
            resp.setContentType("text/html; charset=utf8");
            resp.setStatus(404);
            resp.getWriter().write("您要删除博客的 blogId 有误!");
            return;
        }
        // 3.查询这个blogId对应的blog对象
        BlogDao blogDao = new BlogDao();
        Blog blog = null;
        try {
            blog = blogDao.selectOne(Integer.parseInt(blogId));
            if (blog == null){
                resp.setContentType("text/html; charset=utf8");
                resp.setStatus(404);
                resp.getWriter().write("您要删除的 博客 未找到!");
                return;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        // 4.判断登录的用户是否是这个博客的作者
        if (blog.getUserId() != user.getUserId()){
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("您不能删除别人的博客!");
            return;
        }
        // 5.执行删除操作
        try {
            blogDao.delete(Integer.parseInt(blogId));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        // 6.重定向
        resp.sendRedirect("blogList.html");
    }
}
